import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { 
  User, 
  Settings, 
  History, 
  Bell, 
  Shield, 
  Edit,
  MessageSquare,
  Clock,
  Stethoscope,
  Bot,
  Loader2
} from 'lucide-react'
import { useAuth } from '@/contexts/auth-context'
import { AuthAPI } from '@/services/api'
import { useToast } from '@/hooks/use-toast'

export default function ProfilePage() {
  const [isEditing, setIsEditing] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [isGettingCode, setIsGettingCode] = useState(false)
  const [verificationCode, setVerificationCode] = useState('')
  const [showVerificationInput, setShowVerificationInput] = useState(false)
  const { user, updateUser } = useAuth()
  const { toast } = useToast()
  
  const [userInfo, setUserInfo] = useState({
    id: 0,
    username: '',
    nickname: '',
    name: '',
    email: '',
    mobile: '',
    avatar: '',
    sex: 0,
    status: 1,
    role: '',
    remark: ''
  })

  const [originalUserInfo, setOriginalUserInfo] = useState({
    id: 0,
    username: '',
    nickname: '',
    name: '',
    email: '',
    mobile: '',
    avatar: '',
    sex: 0,
    status: 1,
    role: '',
    remark: ''
  })

  // 页面加载时获取用户信息
  useEffect(() => {
    fetchUserInfo()
  }, [])

  const fetchUserInfo = async () => {
    try {
      setIsLoading(true)
      console.log('Fetching user info...') // 调试日志
      
      const response = await AuthAPI.getCurrentUser()
      console.log('User info response:', response) // 调试日志
      
      if (response.code === 0 && response.data) {
        const userData = response.data
        const userInfoData = {
          id: userData.id,
          username: userData.username,
          nickname: userData.nickname,
          name: userData.nickname || userData.username,
          email: userData.email,
          mobile: userData.mobile,
          avatar: userData.avatar,
          sex: userData.sex,
          status: userData.status,
          role: userData.remark || '普通用户',
          remark: userData.remark || ''
        }
        
        setUserInfo(userInfoData)
        setOriginalUserInfo(userInfoData) // 保存原始数据
        
        // 同时更新认证上下文中的用户信息
        updateUser({
          ...userData,
          name: userData.nickname || userData.username,
          role: userData.remark || '普通用户',
          remark: userData.remark,
          isLoggedIn: true
        })
        
        toast({
          title: "信息加载成功",
          description: "已获取最新的个人信息",
        })
      } else {
        toast({
          title: "获取信息失败",
          description: response.message || "无法获取用户信息",
          variant: "destructive"
        })
      }
    } catch (error) {
      console.error('Failed to fetch user info:', error)
      toast({
        title: "获取信息失败",
        description: error instanceof Error ? error.message : "网络错误，请稍后重试",
        variant: "destructive"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const chatHistory = [
    {
      id: 1,
      agent: 'medical',
      agentName: '医疗智能体',
      lastMessage: '建议您多休息，保持充足的睡眠...',
      timestamp: '2024-01-15 14:30',
      messageCount: 12
    },
    {
      id: 2,
      agent: 'super',
      agentName: '超级智能体',
      lastMessage: '我可以帮您制定一个学习计划...',
      timestamp: '2024-01-14 09:15',
      messageCount: 8
    },
    {
      id: 3,
      agent: 'medical',
      agentName: '医疗智能体',
      lastMessage: '这种症状通常是由于压力过大导致的...',
      timestamp: '2024-01-13 16:45',
      messageCount: 15
    }
  ]

  // 获取验证码
  const handleGetVerificationCode = async () => {
    if (!userInfo.email) {
      toast({
        title: "获取验证码失败",
        description: "请先输入邮箱地址",
        variant: "destructive"
      })
      return
    }

    setIsGettingCode(true)
    try {
      const response = await AuthAPI.getCode(userInfo.email)
      
      if (response.code === 0) {
        toast({
          title: "验证码已发送",
          description: "请查收邮箱中的验证码",
        })
        setShowVerificationInput(true)
      } else {
        toast({
          title: "获取验证码失败",
          description: response.message || "发送失败，请稍后重试",
          variant: "destructive"
        })
      }
    } catch (error) {
      console.error('Get code error:', error)
      toast({
        title: "获取验证码失败",
        description: error instanceof Error ? error.message : "网络错误，请稍后重试",
        variant: "destructive"
      })
    } finally {
      setIsGettingCode(false)
    }
  }

  // 保存用户信息
  const handleSave = async () => {
    if (!verificationCode) {
      toast({
        title: "保存失败",
        description: "请输入验证码",
        variant: "destructive"
      })
      return
    }

    setIsSaving(true)
    try {
      // 构建更新请求数据
      const updateData = {
        username: userInfo.username,
        nickname: userInfo.nickname,
        email: userInfo.email,
        mobile: userInfo.mobile,
        avatar: userInfo.avatar,
        sex: userInfo.sex,
        code: verificationCode
      }

      console.log('Updating user with data:', updateData) // 调试日志

      const response = await AuthAPI.updateUser(updateData)
      
      if (response.code === 0) {
        toast({
          title: "保存成功",
          description: "个人信息已更新",
        })
        
        // 重新获取用户信息
        await fetchUserInfo()
        
        // 退出编辑模式
        setIsEditing(false)
        setShowVerificationInput(false)
        setVerificationCode('')
      } else {
        toast({
          title: "保存失败",
          description: response.message || "更新失败，请检查信息后重试",
          variant: "destructive"
        })
      }
    } catch (error) {
      console.error('Update user error:', error)
      toast({
        title: "保存失败",
        description: error instanceof Error ? error.message : "网络错误，请稍后重试",
        variant: "destructive"
      })
    } finally {
      setIsSaving(false)
    }
  }

  // 取消编辑
  const handleCancel = () => {
    setUserInfo(originalUserInfo) // 恢复原始数据
    setIsEditing(false)
    setShowVerificationInput(false)
    setVerificationCode('')
  }

  const getAgentIcon = (agent: string) => {
    return agent === 'medical' ? Stethoscope : Bot
  }

  const getAgentColor = (agent: string) => {
    return agent === 'medical' ? 'from-blue-500 to-blue-600' : 'from-green-500 to-green-600'
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-green-50 py-8">
      <div className="max-w-4xl mx-auto px-6">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">个人中心</h1>
          <p className="text-gray-600">管理您的个人信息和使用记录</p>
        </div>

        <Tabs defaultValue="profile" className="space-y-6">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="profile" className="flex items-center space-x-2">
              <User className="w-4 h-4" />
              <span>个人信息</span>
            </TabsTrigger>
            <TabsTrigger value="history" className="flex items-center space-x-2">
              <History className="w-4 h-4" />
              <span>聊天记录</span>
            </TabsTrigger>
            <TabsTrigger value="settings" className="flex items-center space-x-2">
              <Settings className="w-4 h-4" />
              <span>设置</span>
            </TabsTrigger>
          </TabsList>

          {/* Profile Tab */}
          <TabsContent value="profile">
            <Card className="border-0 bg-white/80 backdrop-blur-sm">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center space-x-2">
                    <User className="w-5 h-5" />
                    <span>个人信息</span>
                  </CardTitle>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => isEditing ? handleCancel() : setIsEditing(true)}
                  >
                    <Edit className="w-4 h-4 mr-2" />
                    {isEditing ? '取消' : '编辑'}
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                {isLoading ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
                    <span className="ml-2 text-gray-600">正在加载用户信息...</span>
                  </div>
                ) : (
                  <>
                    <div className="flex items-center space-x-6">
                      <Avatar className="w-20 h-20">
                        <AvatarFallback className="text-2xl bg-gradient-to-r from-blue-100 to-green-100 text-blue-600">
                          {userInfo.name ? userInfo.name.charAt(0) : 'U'}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <h3 className="text-xl font-semibold text-gray-900">
                          {userInfo.name || userInfo.nickname || userInfo.username || '未设置'}
                        </h3>
                        <p className="text-gray-600">{userInfo.email || '未设置邮箱'}</p>
                        <div className="flex items-center space-x-2 mt-2">
                          <Badge variant="secondary">
                            {userInfo.status === 0 ? '正常用户' : '受限用户'}
                          </Badge>
                        </div>
                      </div>
                    </div>

                    <div className="grid md:grid-cols-2 gap-6">
                      <div className="space-y-2">
                        <Label htmlFor="username">用户名</Label>
                        <Input
                          id="username"
                          value={userInfo.username}
                          disabled={true}
                          className="bg-gray-50"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="nickname">昵称</Label>
                        <Input
                          id="nickname"
                          value={userInfo.nickname}
                          onChange={(e) => setUserInfo({...userInfo, nickname: e.target.value})}
                          disabled={!isEditing}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="email">邮箱</Label>
                        <Input
                          id="email"
                          type="email"
                          value={userInfo.email}
                          onChange={(e) => setUserInfo({...userInfo, email: e.target.value})}
                          disabled={!isEditing}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="mobile">手机号</Label>
                        <Input
                          id="mobile"
                          value={userInfo.mobile}
                          onChange={(e) => setUserInfo({...userInfo, mobile: e.target.value})}
                          disabled={!isEditing}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="sex">性别</Label>
                        <Input
                          id="sex"
                          value={userInfo.sex === 1 ? '男' : userInfo.sex === 2 ? '女' : '未设置'}
                          disabled={true}
                          className="bg-gray-50"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="role">用户角色</Label>
                        <Input
                          id="role"
                          value={userInfo.role || '普通用户'}
                          disabled={true}
                          className="bg-gray-50"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="id">用户ID</Label>
                        <Input
                          id="id"
                          value={userInfo.id.toString()}
                          disabled={true}
                          className="bg-gray-50"
                        />
                      </div>
                    </div>
                  </>
                )}

                {isEditing && (
                  <div className="space-y-4">
                    {/* 获取验证码按钮 */}
                    {!showVerificationInput && (
                      <div className="flex justify-center">
                        <Button
                          onClick={handleGetVerificationCode}
                          disabled={isGettingCode || !userInfo.email}
                          className="bg-gradient-to-r from-green-600 to-green-700"
                        >
                          {isGettingCode ? (
                            <>
                              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                              发送中...
                            </>
                          ) : (
                            '获取验证码'
                          )}
                        </Button>
                      </div>
                    )}

                    {/* 验证码输入 */}
                    {showVerificationInput && (
                      <div className="space-y-2">
                        <Label htmlFor="verification-code">邮箱验证码</Label>
                        <div className="flex space-x-2">
                          <Input
                            id="verification-code"
                            type="text"
                            placeholder="请输入验证码"
                            value={verificationCode}
                            onChange={(e) => setVerificationCode(e.target.value)}
                            className="flex-1"
                          />
                          <Button
                            onClick={handleGetVerificationCode}
                            disabled={isGettingCode || !userInfo.email}
                            variant="outline"
                            className="whitespace-nowrap"
                          >
                            {isGettingCode ? "发送中..." : "重新发送"}
                          </Button>
                        </div>
                      </div>
                    )}

                    {/* 保存和取消按钮 */}
                    <div className="flex space-x-4">
                      <Button 
                        onClick={handleSave} 
                        disabled={isSaving || !verificationCode}
                        className="bg-gradient-to-r from-blue-600 to-blue-700"
                      >
                        {isSaving ? (
                          <>
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                            保存中...
                          </>
                        ) : (
                          '保存更改'
                        )}
                      </Button>
                      <Button variant="outline" onClick={handleCancel} disabled={isSaving}>
                        取消
                      </Button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* History Tab */}
          <TabsContent value="history">
            <Card className="border-0 bg-white/80 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <History className="w-5 h-5" />
                  <span>聊天记录</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {chatHistory.map((chat) => {
                    const Icon = getAgentIcon(chat.agent)
                    return (
                      <div key={chat.id} className="flex items-center space-x-4 p-4 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
                        <div className={`w-12 h-12 bg-gradient-to-r ${getAgentColor(chat.agent)} rounded-xl flex items-center justify-center`}>
                          <Icon className="w-6 h-6 text-white" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center space-x-2 mb-1">
                            <h3 className="font-semibold text-gray-900">{chat.agentName}</h3>
                            <Badge variant="outline" className="text-xs">
                              <MessageSquare className="w-3 h-3 mr-1" />
                              {chat.messageCount}条消息
                            </Badge>
                          </div>
                          <p className="text-gray-600 text-sm truncate">{chat.lastMessage}</p>
                          <div className="flex items-center space-x-1 mt-1 text-xs text-gray-500">
                            <Clock className="w-3 h-3" />
                            <span>{chat.timestamp}</span>
                          </div>
                        </div>
                        <Button variant="ghost" size="sm">
                          查看详情
                        </Button>
                      </div>
                    )
                  })}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Settings Tab */}
          <TabsContent value="settings">
            <div className="space-y-6">
              <Card className="border-0 bg-white/80 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Bell className="w-5 h-5" />
                    <span>通知设置</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-medium text-gray-900">消息通知</h3>
                      <p className="text-sm text-gray-600">接收新消息的推送通知</p>
                    </div>
                    <Button variant="outline" size="sm">开启</Button>
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-medium text-gray-900">邮件通知</h3>
                      <p className="text-sm text-gray-600">接收重要更新的邮件通知</p>
                    </div>
                    <Button variant="outline" size="sm">开启</Button>
                  </div>
                </CardContent>
              </Card>

              <Card className="border-0 bg-white/80 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Shield className="w-5 h-5" />
                    <span>隐私与安全</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-medium text-gray-900">数据加密</h3>
                      <p className="text-sm text-gray-600">所有数据传输均采用SSL加密</p>
                    </div>
                    <Badge variant="secondary" className="bg-green-100 text-green-700">已启用</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-medium text-gray-900">隐私保护</h3>
                      <p className="text-sm text-gray-600">严格保护用户隐私信息</p>
                    </div>
                    <Badge variant="secondary" className="bg-green-100 text-green-700">已启用</Badge>
                  </div>
                  <Button variant="outline" className="w-full">
                    查看隐私政策
                  </Button>
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}
